package com.nd.service.wx;

import cn.hutool.core.date.DateTime;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nd.dao.*;
import com.nd.pojo.bean.*;
import com.nd.pojo.vo.CommentsListVo;
import com.nd.pojo.vo.GoodsListVo;
import com.nd.pojo.vo.wx.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: project2mall
 * @description:
 * @author: shit_code_builder
 * @create: 2021-06-08 11:56
 **/
@Service
public class WXGoodsService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    CategoryMapper categoryMapper;

    @Autowired
    GoodsMapper goodsMapper;

    @Autowired
    FootprintMapper footprintMapper;

    @Autowired
    CommentMapper commentMapper;

    @Autowired
    AttributeMapper attributeMapper;

    @Autowired
    BrandMapper brandMapper;

    @Autowired
    GrouponRulesMapper grouponRulesMapper;

    @Autowired
    GrouponMapper grouponMapper;

    @Autowired
    IssueMapper issueMapper;

    @Autowired
    GoodsProductMapper goodsProductMapper;

    @Autowired
    GoodsSpecificationMapper goodsSpecificationMapper;



    public BaseRespWXVo<GoodsCategoryVO> selectCategoryById(Integer id) {
        if (id==null)return BaseRespWXVo.fail("查询失败");

        Category category = categoryMapper.selectByPrimaryKey(id);
        if (category==null)return BaseRespWXVo.ok(null,"成功,但未完全成功");
        if (category.getPid().compareTo(0)==0){
            CategoryExample categoryExample = new CategoryExample();
            categoryExample.createCriteria().andPidEqualTo(category.getId());

            List<Category> categories = categoryMapper.selectByExample(categoryExample);
            category=categories.get(0);
        }



        CategoryExample categoryExample = new CategoryExample();
        categoryExample.createCriteria().andPidEqualTo(category.getPid());

        List<Category> categories = categoryMapper.selectByExample(categoryExample);

        Category parentcategory = categoryMapper.selectByPrimaryKey(category.getPid());

        GoodsCategoryVO build = GoodsCategoryVO.builder().currentCategory(category).parentCategory(parentcategory).brotherCategory(categories).build();


    return BaseRespWXVo.ok(build);
    }

    public BaseRespWXVo<WXGoodListVO> selectGoodBycategoryId(Integer categoryId, Integer page, Integer size) {

        PageHelper.startPage(page,size);

        WXGoodListVO goodsListVo = new WXGoodListVO();

        GoodsExample goodsExample = new GoodsExample();
        GoodsExample.Criteria criteria = goodsExample.createCriteria().andCategoryIdEqualTo(categoryId);

        List<Goods> goods = goodsMapper.selectByExample(goodsExample);

        goodsListVo.setGoodsList(goods);

        PageInfo<Goods> objectPageInfo = new PageInfo<>(goods);
        long total = objectPageInfo.getTotal();
        goodsListVo.setCount(total);


        return BaseRespWXVo.ok(goodsListVo);
    }

    public BaseRespWXVo<GoodDetailVO> selectGoodDetail(Integer id) {

        if (goodsMapper.selectByPrimaryKey(id)==null){
            return BaseRespWXVo.fail("该商品不存在");
        }

        //插入查询足迹
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        if (user!=null){
            Integer uid = user.getId();
            FootprintExample footprintExample = new FootprintExample();
            footprintExample.createCriteria().andUserIdEqualTo(uid).andGoodsIdEqualTo(id);
            List<Footprint> footprints = footprintMapper.selectByExample(footprintExample);
            if (footprints.isEmpty()){
                Footprint footBuild = Footprint.builder().userId(uid).goodsId(id).addTime(DateTime.now()).updateTime(DateTime.now()).deleted(false).build();
                int insert = footprintMapper.insert(footBuild);
            }else {
                footprints.get(0).setUpdateTime(DateTime.now());
                footprintMapper.updateByPrimaryKey(footprints.get(0));
            }

        }


        //构建商品细节VO
        GoodDetailVO goodDetailVO = new GoodDetailVO();
        Goods goods = goodsMapper.selectByPrimaryKey(id);
        goodDetailVO.setInfo(goods);

        AttributeExample attributeExample = new AttributeExample();
        AttributeExample.Criteria criteria = attributeExample.createCriteria().andGoodsIdEqualTo(id).andDeletedEqualTo(false);
        List<Attribute> attributes = attributeMapper.selectByExample(attributeExample);
        goodDetailVO.setAttribute(attributes);

        Brand brand = brandMapper.selectByPrimaryKey(goods.getBrandId());
        goodDetailVO.setBrand(brand);

        CommentExample commentExample = new CommentExample();
        commentExample.createCriteria().andValueIdEqualTo(goods.getId()).andDeletedEqualTo(false);
        List<Comment> comments = commentMapper.selectByExample(commentExample);
        WXCommentsListVo commentsListVo = new WXCommentsListVo();
        ArrayList<CommentZJTVO> commentZJTVOS = new ArrayList<>();
        for (Comment comment : comments) {
            Integer userId = comment.getUserId();
            User userPlus = userMapper.selectByPrimaryKey(userId);
            String avatar = user.getAvatar();
            CommentZJTVO build = CommentZJTVO.builder().addTime(comment.getAddTime()).avatar(avatar).content(comment.getContent()).id(comment.getId()).nickname(userPlus.getNickname()).picList(comment.getPicUrls()).build();
            commentZJTVOS.add(build);
        }
        commentsListVo.setData(commentZJTVOS);
        commentsListVo.setCount(comments.size());
        goodDetailVO.setComment(commentsListVo);

        GrouponRulesExample grouponRulesExample = new GrouponRulesExample();
        grouponRulesExample.createCriteria().andGoodsIdEqualTo(goods.getId()).andDeletedEqualTo(false);
        List<Groupon> groupons = new ArrayList<>();
        List<GrouponRules> grouponRules = grouponRulesMapper.selectByExample(grouponRulesExample);
        for (GrouponRules rule : grouponRules) {
            Groupon groupon =grouponMapper.selectByRulesId(rule.getId());
            groupons.add(groupon);
        }
        goodDetailVO.setGroupon(groupons);

        IssueExample issueExample = new IssueExample();
        List<Issue> issues = issueMapper.selectByExample(issueExample);
        goodDetailVO.setIssue(issues);

        GoodsProductExample goodsProductExample = new GoodsProductExample();
       goodsProductExample.createCriteria().andGoodsIdEqualTo(goods.getId()).andDeletedEqualTo(false);
        List<GoodsProduct> goodsProducts = goodsProductMapper.selectByExample(goodsProductExample);
        goodDetailVO.setProductList(goodsProducts);

        GoodsSpecificationExample goodsSpecificationExample = new GoodsSpecificationExample();
        goodsSpecificationExample.createCriteria().andGoodsIdEqualTo(goods.getId()).andDeletedEqualTo(false);
        List<GoodsSpecification> goodsSpecifications = goodsSpecificationMapper.selectByExample(goodsSpecificationExample);
        HashSet<String> SpecificationName = new HashSet<>();
        for (GoodsSpecification goodsSpecification : goodsSpecifications) {
        SpecificationName.add(goodsSpecification.getSpecification());
        }
        List<SpecificationVO> specificationVOS = new ArrayList<>();
        for (String s : SpecificationName) {
            SpecificationVO specificationVO = new SpecificationVO();
            specificationVO.setName(s);
            List<GoodsSpecification> collect = goodsSpecifications.stream().filter(o -> s.equals(o.getSpecification())).collect(Collectors.toList());
            specificationVO.setValueList(collect);
            specificationVOS.add(specificationVO);
        }
        goodDetailVO.setSpecificationList(specificationVOS);

        return BaseRespWXVo.ok(goodDetailVO);
    }

    public ArrayList<GoodRelatedVO> selectGoodRelated(Integer id) {

        Goods goodMain = goodsMapper.selectByPrimaryKey(id);

        GoodsExample goodsExample = new GoodsExample();
        goodsExample.createCriteria().andCategoryIdEqualTo(goodMain.getCategoryId()).andDeletedEqualTo(false);
        List<Goods> goods = goodsMapper.selectByExample(goodsExample);
        ArrayList<GoodRelatedVO> goodRelatedVOS = new ArrayList<>();

        for (int i = 0; i < ((goods.size()>=6)? 6:goods.size()); i++) {
            Goods good = goods.get(i);
            if (good.getId()!=goodMain.getId()){
                GoodRelatedVO build = GoodRelatedVO.builder().brief(good.getBrief()).counterPrice(good.getCounterPrice().doubleValue()).id(good.getId()).isHot(good.getIsHot()).isNew(good.getIsNew()).name(good.getName()).picUrl(good.getPicUrl()).retailPrice(good.getRetailPrice().doubleValue()).build();
                goodRelatedVOS.add(build);
            }

        }


    return goodRelatedVOS;
    }
}
